import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:provider/provider.dart';

import 'package:shop/views/banner_view.dart';
import 'package:shop/views/search_view.dart';
import 'package:shop/vm/home_vm.dart';
import 'package:shop/util/color.dart';
import 'package:shop/router/router.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final viewModel = HomeViewModel();

  final refreshController = RefreshController();

  @override
  void initState() {
    super.initState();

    viewModel.getHomeData();
    viewModel.getListData(true);
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<HomeViewModel>.value(
      value: viewModel,
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
            iconTheme: IconThemeData(color: Colors.white),
            title: Text('黑猫优购', style: TextStyle(color: Colors.white)),
            backgroundColor: HexColor.fromHex('#C00000')),
        body: Column(
          children: [
            SearchView(
              callback: (text) {
                Navigator.pushNamed(context, goodsPage, arguments: text);
              },
            ),
            Expanded(
              child: SmartRefresher(
                enablePullDown: true,
                enablePullUp: true,
                header: WaterDropHeader(),
                footer: ClassicFooter(),
                controller: refreshController,
                child: SingleChildScrollView(
                  keyboardDismissBehavior:
                      ScrollViewKeyboardDismissBehavior.onDrag,
                  child: Column(
                    children: [bannerView(), navList(), productList()],
                  ),
                ),
                onRefresh: () {
                  viewModel.getListData(false);
                  refreshController.refreshCompleted();
                },
                onLoading: () {
                  viewModel.getListData(true);
                  refreshController.loadNoData();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget bannerView() {
    return Consumer<HomeViewModel>(
      builder: (context, value, child) {
        return BannerView(
          bannerList: value.bannerList,
          height: 200.0,
        );
      },
    );
  }

  Widget navList() {
    return Consumer<HomeViewModel>(builder: (context, value, child) {
      return Container(
        padding: EdgeInsets.all(20),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: value.catitemsList.map((element) {
            final imageUrl =
                (element.imageSrc ?? '').replaceAll('https', 'http');
            return CachedNetworkImage(
              imageUrl: imageUrl,
              width: 60,
              height: 60,
            );
          }).toList(),
        ),
      );
    });
  }

  Widget productList() {
    return Consumer<HomeViewModel>(
      builder: (context, value, child) {
        return ListView.builder(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemCount: value.floorList.length,
          itemBuilder: (BuildContext context, int index) {
            final productData = viewModel.floorList[index];
            final titleUrl = (productData.floorTitle?.imageSrc ?? '')
                .replaceAll('https', 'http');

            final width = (MediaQuery.of(context).size.width - 6) / 3;
            final height = (200 - 3) / 2.0;

            List<Widget> widgetArray = [];
            for (var i = 0; i < (productData.productList?.length ?? 0); i++) {
              final product = productData.productList?[i];
              final imageUrl =
                  (product?.imageSrc ?? '').replaceAll('https', 'http');
              final widget = InkWell(
                child: CachedNetworkImage(
                  imageUrl: imageUrl,
                  fit: BoxFit.cover,
                  width: width,
                  height: i == 0 ? 200 : height,
                ),
                onTap: () {
                  final name = product?.navigatorUrl?.split('=').last;
                  Navigator.pushNamed(context, goodsPage, arguments: name);
                },
              );
              widgetArray.add(widget);
            }
            return Column(
              children: [
                CachedNetworkImage(
                  imageUrl: titleUrl,
                  fit: BoxFit.fitWidth,
                  height: 40,
                ),
                Row(
                  children: [
                    widgetArray.first,
                    SizedBox(
                      width: 3,
                    ),
                    Expanded(
                      child: Wrap(
                        spacing: 3,
                        runSpacing: 3,
                        children: widgetArray.sublist(1, widgetArray.length),
                      ),
                    )
                  ],
                )
              ],
            );
          },
        );
      },
    );
  }
}
